<?php 
/**
 * $ModDesc
 * 
 * @version		$Id: helper.php $Revision
 * @package		modules
 * @subpackage	$Subpackage
 * @copyright	Copyright (C) May 2010 LandOfCoder.com <@emai:landofcoder@gmail.com>. All rights reserved.
 * @website 	htt://landofcoder.com
 * @license		GNU General Public License version 2
 */

if(!class_exists('VirtueMartControllerVirtuemart')) require(JPATH_SITE.DS.'components'.DS.'com_virtuemart'.DS.'controllers'.DS.'virtuemart.php');
if (!class_exists( 'VirtueMartModelProduct' )){
   JLoader::import( 'product', JPATH_ADMINISTRATOR . DS . 'components' . DS . 'com_virtuemart' . DS . 'models' );
}


if( !class_exists('LofSlideShowGroupVirtuemart') ) {

	class LofSlideShowGroupVirtuemart extends LofSlideShowGroupBase{
		/**
		 * @var string $__name 
		 *
		 * @access private;
		 */
		var $__name = 'virtuemart';
		
		/**
		 * override get List of Item by the module's parameters
		 */
		public function getListByParameters( $params ){
			if( !LofSlideShowGroupVirtuemart::isVirtueMartExisted() ){
				return array();
			} 
			return $this->__getList( $params );
		}
		
		/**
		 * check virtuemart is installed or not ?
		 */
		public function isVirtueMartExisted(){
			return  is_dir( JPATH_ADMINISTRATOR.DS.'components'.DS.'com_virtuemart' );
		}
		
		/**
		 * get list of product 
		 *
		 *
		 * @access private
		 */
		public function __getList( $params ){
			
			global $sess, $mm_action_url;
			
			$db = JFactory::getDBO();
            $currency = CurrencyDisplay::getInstance( );
			$limit 	       = $params->get( 'limit_items', 10 );
			//$ordering      = str_replace( '_', '  ', $ordering );
			$thumbWidth    = (int)$params->get( 'thumbnail_width', 35 );
			$thumbHeight   = (int)$params->get( 'thumbnail_height', 60 );
			$imageHeight   = (int)$params->get( 'main_height', 300 ) ;
			$imageWidth    = (int)$params->get( 'main_width', 660 ) ;
			$isThumb       = $params->get( 'auto_renderthumb',1);
			$descriptionMaxChars = $params->get( 'description_max_chars', 100 );	
			$extraURL 	   = $params->get('open_target')!='modalbox'?'':'&tmpl=component'; 
            
			$condition = $this->buildConditionQuery( $params );
            $getorder  = $this->getOrder( $params );
            $query 	= ' SELECT p.*, l.product_s_desc, l.product_desc, l.metadesc, l.product_name, l.metakey, l.slug, pc.virtuemart_category_id, pc.ordering '
					. ' 	, cl.category_name, cl.category_description, cl.slug as slug_catlang'
					. ' 	, pp.virtuemart_product_price_id, pp.product_price, pp.override, pp.product_override_price, pp.product_tax_id, pp.product_discount_id, pp.product_currency'
					. ' 	, pp.product_price_vdate, pp.product_price_edate, pp.price_quantity_start, pp.price_quantity_end'
					. ' 	, pm.virtuemart_media_id, m.virtuemart_vendor_id, m.file_title, m.file_description, m.file_mimetype, m.file_type, m.file_url, m.file_url_thumb, m.file_is_product_image, m.file_is_downloadable, m.file_is_forSale'
					. ' 	, s.virtuemart_shoppergroup_id, s.shopper_group_name, s.shopper_group_desc, s.custom_price_display'
					. ' FROM `#__virtuemart_products` as p ';
            $query  .= ' JOIN `#__virtuemart_products_'.VMLANG.'` AS l using (`virtuemart_product_id`)';
            $query  .= ' LEFT JOIN `#__virtuemart_product_categories` AS pc ON p.`virtuemart_product_id` = pc.`virtuemart_product_id`
			             LEFT JOIN `#__virtuemart_categories_'.VMLANG.'` as cl ON cl.`virtuemart_category_id` = pc.`virtuemart_category_id`
                         LEFT OUTER JOIN `#__virtuemart_categories` as c ON cl.`virtuemart_category_id` = c.`virtuemart_category_id`';
            $query  .= $condition;
			$query  .= ' LEFT JOIN `#__virtuemart_product_prices` as pp ON p.`virtuemart_product_id` = pp.`virtuemart_product_id` ';
            $query  .= ' LEFT JOIN `#__virtuemart_product_medias` as pm ON p.`virtuemart_product_id` = pm.`virtuemart_product_id`
                         LEFT OUTER JOIN `#__virtuemart_medias` as m ON m.`virtuemart_media_id` = pm.`virtuemart_media_id`';
            $query  .= ' LEFT JOIN `#__virtuemart_product_shoppergroups` as ps ON p.`virtuemart_product_id` = ps.`virtuemart_product_id`
                         LEFT OUTER JOIN `#__virtuemart_shoppergroups` as s ON ps.`virtuemart_shoppergroup_id` = s.`virtuemart_shoppergroup_id`';
            $query .= ' WHERE p.published = 1 AND c.published = 1 ';
            $query .= ' GROUP BY p.`virtuemart_product_id`';
            $query .= ' ORDER BY  ' . $getorder;
			$query .= ' LIMIT '. $limit;
            $db->setQuery($query);
			$data = $db->loadObjectList();
			if( !empty($data) ){
				foreach( $data as $key => $item ){
					$tmpimage =  $item->file_url;
                    if( !(strtolower(substr($tmpimage, 0, 4)) == 'http') ) {
            			$file_url = $item->file_url;
            			$file_alt = $item->file_title;
            		} else {
            			$rel_path = str_replace('/',DS,$item->file_url_folder);
            			$fullSizeFilenamePath = JPATH_ROOT.DS.$rel_path.$item->file_name.'.'.$item->file_extension;
            			if (!file_exists($fullSizeFilenamePath)) {
            				$file_url = $item->theme_url.'assets/images/vmgeneral/'.VmConfig::get('no_image_found');
            				$file_alt = JText::_('COM_VIRTUEMART_NO_IMAGE_FOUND').' '.$item->file_description;
            			} else {
            				$file_url = $item->file_url;
            				$file_alt = $item->file_meta;
            			}
            		}
                    if(!class_exists('calculationHelper')) require(JPATH_VM_ADMINISTRATOR.DS.'helpers'.DS.'calculationh.php');
                    $calculator = calculationHelper::getInstance();
                    $item->categories = $item->virtuemart_category_id;
                    $item->prices = $this->getPrice($item,array(),1);
                    
                    $item->salesPrice = $currency->createPriceDiv('salesPrice','',$item->prices,true);
                    if ($item->prices['salesPriceWithDiscount']>0 && $item->prices['salesPriceWithDiscount'] != $item->prices['salesPrice']){
                        $item->salesPriceWithDiscount = $currency->createPriceDiv('salesPriceWithDiscount','',$item->prices,true);
                    }else{
                        $item->salesPriceWithDiscount = '';
                    }
                    
                    $item->costPrice = $currency->createPriceDiv ( 'costPrice', '', $item->prices );
                    $item->variantModification = $currency->createPriceDiv ( 'variantModification', '', $item->prices );
    				$item->basePrice = $currency->createPriceDiv ( 'basePrice', '', $item->prices );
    				$item->basePriceVariant = $currency->createPriceDiv ( 'basePriceVariant', '', $item->prices );
    				$item->basePriceWithTax = $currency->createPriceDiv ( 'basePriceWithTax', '', $item->prices );
    				$item->discountedPriceWithoutTax = $currency->createPriceDiv ( 'discountedPriceWithoutTax', '', $item->prices );
    				$item->priceWithoutTax = $currency->createPriceDiv ( 'priceWithoutTax', '', $item->prices );
    				$item->discountAmount = $currency->createPriceDiv ( 'discountAmount', '', $item->prices );
    				$item->taxAmount = $currency->createPriceDiv ( 'taxAmount', '', $item->prices ); 
                    
                    
                    $item->file_url = $file_url;
                    $item->file_alt = $file_alt;
					$cid = $item->virtuemart_category_id;
					$item->title = $item->product_name;
					$item->introtext =   $item->product_s_desc ;
					$item->fulltext =   $item->product_desc ;
					$item->description = $this->substring( $item->fulltext, $descriptionMaxChars, true);	
                    $item->link = JRoute::_('index.php?option=com_virtuemart&view=productdetails&virtuemart_product_id='.$item->virtuemart_product_id.'&virtuemart_category_id='.$item->virtuemart_category_id);
					
					$item->mainImage = $item->thumbnail = ''; 
					
					if( $item->file_url&&$image=self::renderThumb( $item->file_url, $imageWidth, $imageHeight, $item->product_name, $isThumb ) ){
						$item->mainImageURL = $image;
						$item->mainImage = '<img src="'.$image.'"  title="'.$item->product_name.'" alt="'.$item->product_name.'">';
					}
					if( $item->file_url&&$image=self::renderThumb( $item->file_url, $thumbWidth, $thumbHeight, $item->product_name, $isThumb ) ){
						$item->thumbnail = '<img src="'.$image.'" title="'.$item->product_name.'" alt="'.$item->product_name.'">';
						$item->thumbnailURL = $image; 
					}
					
					$data[$key]=$item;
				}
				return $data;
			}
			return array();
		}
		
        
        public function getPrice($product,$customVariant,$quantity){
            //echo "<pre>";print_r($product);die;
        	$this->_db = JFactory::getDBO();
        	if(!is_object($product)){
        		$product = $this->getProduct($product,true,false,true);
        	}
            $calculator = calculationHelper::getInstance();
        	// Calculate the modificator
        	$variantPriceModification = $calculator->calculateModificators($product,$customVariant);
            
        	$prices = $calculator->getProductPrices($product,$product->virtuemart_category_id,$variantPriceModification,$quantity);
           
        	return $prices;
        
        }
        public function getOrder( $params ){
            $ordering      = $params->get( 'vm_ordering', 'created_on_asc' ); 
            if( trim($ordering) == 'created_on_asc' ){
				$ordering = " created_on ASC ";
			}elseif( trim($ordering) == 'created_on_desc' ){
                $ordering = " created_on DESC ";
			}elseif( trim($ordering) == 'product_price_asc' ){
                $ordering = " product_price ASC ";
			}elseif( trim($ordering) == 'product_price_desc' ){
                $ordering = " product_price DESC ";
			}elseif( trim($ordering) == 'product_ordered_asc' ){
                $ordering = " product_ordered ASC ";
			}elseif( trim($ordering) == 'product_ordered_desc' ){
                $ordering = " product_ordered DESC ";
			}elseif( trim($ordering) == 'rand' ){
				$ordering = " RAND() ";
			}
            return $ordering;
        }
        
		/**
		 * build condition query base parameter  
		 * 
		 * @param JParameter $params;
		 * @return string.
		 */
		  function buildConditionQuery( $params ){
			$source = trim($params->get( 'vm_source', 'vm_category' ) );
			if( $source == 'vm_category' ){
				$catids = $params->get( 'vm_category','0');
			
				if( !$catids ){
					return '';
				}
				$catids = !is_array($catids) ? $catids : '"'.implode('","',$catids).'"';
				$condition = ' AND  pc.virtuemart_category_id IN( '.$catids.' )';
			} else {
				$ids = preg_split('/,/',$params->get( 'vm_items_ids',''));	
				$tmp = array();
				foreach( $ids as $id ){
					$tmp[] = (int) trim($id);
				}
				$condition = " AND pc.virtuemart_product_id IN('". implode( "','", $tmp ) ."')";
			}
			return $condition;
		}
	}
}
?>